import java.time.Year;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BinaryTree {
    static class TreeNode{
        public char val;
        public TreeNode right;
        public TreeNode left;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode createTree(){
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }


    public boolean isSameTree(TreeNode p,TreeNode q){
        if (p == null && q != null || p != null && q == null){
            return false;
        }
        //两个都为空
        if (p == null && q == null){
            return true;
        }
        //一定是两个都不为空
        if (p.val != q.val){
            return false;
        }
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
    public boolean isSubtree(TreeNode root,TreeNode subRoot){
        if (root == null){
            return false;
        }
        if (isSameTree(root, subRoot)){
            return true;
        }
        if (isSubtree(root.left,subRoot)){
            return true;
        }
        if (isSubtree(root.right,subRoot)){
            return true;
        }
        return false;
    }

    public TreeNode invertTree(TreeNode root){
        if (root == null){
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
         invertTree(root.left);
         invertTree(root.right);
         return root;
    }

    public int getHeight(TreeNode root){
        if (root == null){
            return 0;
        }
        int leftHight = getHeight(root.left);
        int rightHight = getHeight(root.right);
        return leftHight > rightHight ? leftHight +1 : rightHight +1;
    }
    public boolean isBalanced(TreeNode root){
        if (root == null){
            return true;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return Math.abs(leftHeight - rightHeight) <= 1
                && isBalanced(root.left)
                &&isBalanced(root.right);
    }
}
